package com.sopaths.connect;

import java.util.Map;

import javax.annotation.Resource;
import javax.inject.Named;

import org.apache.log4j.Logger;

import com.sopaths.contract.connect.OAuthToken;
import com.sopaths.contract.domain.LoginType;
import com.sopaths.contract.domain.User;

@Named
public class SopathsConnect {

	@Resource(name = "connectAdapters")
	private Map<LoginType, ConnectAdapter> connectAdapters;

	private final Logger logger = Logger.getLogger(SopathsConnect.class);

	public String getAuthorizeURL(LoginType loginType) {
		ConnectAdapter connectAdapter = getConnectAdapter(loginType);
		String url = connectAdapter.getAuthorizeURL();
		return url;
	}

	public OAuthToken getToken(LoginType loginType) {
		ConnectAdapter connectAdapter = getConnectAdapter(loginType);
		OAuthToken token = connectAdapter.getToken();
		return token;
	}

	public User getUserInfo(LoginType loginType) {
		OAuthToken token = getToken(loginType);
		User user = getUserInfo(token, loginType);
		return user;
	}

	public User getUserInfo(OAuthToken token, LoginType loginType) {
		ConnectAdapter connectAdapter = getConnectAdapter(loginType);
		User user = connectAdapter.getUserInfo(token);
		return user;
	}

	private ConnectAdapter getConnectAdapter(LoginType loginType) {
		ConnectAdapter connectAdapter = connectAdapters.get(loginType);
		if (connectAdapter == null) {
			logger.error("Unknown login type. Type: " + loginType);
			throw new IllegalArgumentException("Unknown login type: " + loginType);
		}
		return connectAdapter;
	}

}
